package com.bailun91.auth.shiro;

import com.bailun91.auth.dto.RoleDto;
import com.bailun91.auth.dto.UserDto;
import com.bailun91.auth.entity.Permission;
import com.bailun91.auth.entity.User;
import com.bailun91.auth.jwt.JwtToken;
import com.bailun91.auth.jwt.JwtUtil;
import com.bailun91.auth.service.UserService;
import com.bailun91.auth.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


public class JwtRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /*
     * 获取用户角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        System.out.println("ShiroRealm的 doGetAuthorizationInfo 鉴权方法执行了");

       String username = JwtUtil.getUserNameFromToken(principal.toString());
        UserDto userDto = userService.findAllUserInfoByUsername(username);


        List<String> stringRoleList = new ArrayList<>();
        List<String> stringPermissionList = new ArrayList<>();


        List<RoleDto> roleList = userDto.getRoleDtoList();

        for (RoleDto roleDto : roleList) {
            stringRoleList.add(roleDto.getName());

            List<Permission> permissionList = roleDto.getPermissionList();

            for (Permission p : permissionList) {
                if (p != null) {
                    stringPermissionList.add(p.getPerms());
                }
            }
        }

        System.out.println(stringRoleList);
        System.out.println("................\n");
        System.out.println(stringPermissionList);


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(stringRoleList);
        simpleAuthorizationInfo.addStringPermissions(stringPermissionList);

        return simpleAuthorizationInfo;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

        System.out.println("ShiroRealm的 doGetAuthorizationInfo 登录认证方法执行了");
        String jwtToken = (String) token.getPrincipal();
        String username = JwtUtil.getUserNameFromToken(jwtToken);

        if (username == null) {
            throw new AuthenticationException("token认证失败！");
        }

        System.out.println(username);
        User user = userService.findByUsername(username);
        System.out.println(user);

        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                jwtToken,
                username,
                getName());
        return info;
    }

    /**
     * 清除所有缓存
     */
    public void clearCachedAuth(){
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}

